package com.example.demo2.service.impl;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.demo2.common.config.redis.RedisUtil;
import com.example.demo2.common.jwt.DefaultToken;
import com.example.demo2.common.jwt.JwtCreator;
import com.example.demo2.entity.*;
import com.example.demo2.mapper.SysRoleMapper;
import com.example.demo2.mapper.SysUserMapper;
import com.example.demo2.mapper.SysUserRoleMapper;
import com.example.demo2.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {


    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private SysUserMapper sysUserMapper;


    @Autowired
    private SysUserRoleMapper userRoleMapper;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;


    @Override
    public DefaultToken login(SysUser user) {

        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authentication);
        SecurityUser securityUser =  (SecurityUser)authenticate.getPrincipal();
        String token = JwtCreator.createToken(user.getUsername());
        redisUtil.set(user.getUsername()+":login", JSON.toJSONString(securityUser));
        DefaultToken defaultToken = new DefaultToken();
        defaultToken.setToken(token);
        defaultToken.setDetails(securityUser);
        return defaultToken;

    }

    @Override
    public Object getUserInfo() {
        return  SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    }

    @Override
    public void register(SysUser user) {
        String password = user.getPassword();
        String encode = passwordEncoder.encode(password);
        user.setPassword(encode);
        sysUserMapper.insert(user);
        initRole(user.getId());
    }


    private void initRole(Long userId){
        SysRole sysRole = roleMapper.selectOne(new QueryWrapper<SysRole>().lambda().eq(SysRole::getInitRole, 1));
        SysUserRole sysUserRole = new SysUserRole();
        sysUserRole.setRoleId(sysRole.getId());
        sysUserRole.setUserId(userId);
        userRoleMapper.insert(sysUserRole);
    }
}
